// pages/songIndex/songIndex.js
import moment from "moment";
import PubSub from "pubsub-js";
const { globalData } = getApp();

import {
  getSongsUrlV1,
  getSongsDetail
} from '../../api/index'

Page({

  data: {
    isPlaying: false,
    musicId: '',
    songs: {},
    songUrl: '',
    currentTime: "00:00",
    durationTime: "00:00",
    currentWidth: 0
  },

  onLoad(options) {
    this.backgroundAudioManager = wx.getBackgroundAudioManager();
    const { onPause, onPlay, onStop, onTimeUpdate, onEnded } = this.backgroundAudioManager
    const { id } = options
    this.setData({ musicId: id })
    this.getMusicInfo(id)
    if (
        globalData.isMusicPlay && globalData.musicId === id
    ) {
      this.setData({ isPlaying: true });
    }
    onPause(() => {
      this.changeState(false);
    });
    onStop(() => {
      this.changeState(false);
    });
    onPlay(() => {
      this.changeState(true);
      globalData.musicId = id;
    });
    onTimeUpdate(() => {
      const currentTime = moment(this.backgroundAudioManager.currentTime * 1000).format("mm:ss");
      const currentWidth = ( this.backgroundAudioManager.currentTime / this.backgroundAudioManager.duration) * 450;
      this.setData({ currentTime, currentWidth });
    });
    onEnded(() => {
      PubSub.publish("switchType", "next");
    });
    PubSub.subscribe("musicId", async (msg, musicId) => {
      this.getMusicInfo(musicId);
      this.getPlayOrStopControl(true, musicId);
    });
  },

  changeState(isPlaying) {
    this.setData({ isPlaying })
    globalData.isMusicPlay = isPlaying;
  },

  // 歌曲详情
  async getMusicInfo(id) {
    const data  = await getSongsDetail({ ids: id })
    const durationTime = moment(data.songs[0].dt).format("mm:ss")
    this.setData({
      songs: data.songs[0],
      musicId: id,
      durationTime,
    });
    wx.setNavigationBarTitle({
      title: this.data.songs.name,
    });
  },

  // 歌曲是否播放
  async getPlayOrStopControl(isPlaying, id, musicUrl, level = "exhigh") {
    let { pause } =  this.backgroundAudioManager
    if (isPlaying) {
      if (!musicUrl) {
        const { data } = await getSongsUrlV1({ id, level });
        this.setData({
          songUrl: data[0].url
        })
      }
      const { songs, songUrl} = this.data
      this.backgroundAudioManager.src = songUrl;
      this.backgroundAudioManager.title = songs.name;
    } else {
      pause();
    }
  },
  // 播放按钮
  playMusic() {
    let { musicId, songUrl } = this.data;
    const isPlaying = !this.data.isPlaying
    this.setData({ isPlaying })
    this.getPlayOrStopControl(isPlaying, musicId, songUrl)
  },
  // 下一曲 && 上一曲
  switchMusic(event){
    const { stop } = this.backgroundAudioManager;
    const type = event.currentTarget.id;
    stop();
    PubSub.publish("switchType", type);
  }
})